# -*- coding: utf-8 -*-
# @Time    : 2021/8/14 12:21
# @Author  : Flora.Chen
# @File    : handle_email.py
# @Software: PyCharm
# @Desc: python自带的SMTP模块发送邮件

import smtplib
from email.mime.text import MIMEText  # 用来发送邮件
from email.mime.application import MIMEApplication  # 用来添加附件
from email.mime.multipart import MIMEMultipart  # 用来构造多组件邮件
from email.header import Header


class HandleEmail:
    """邮件处理类"""

    def __init__(self, host, port, mail_user, mail_auth_code, sender, recipients):
        """
        初始化邮件服务器信息
        :param host: 邮箱服务器地址
        :param port: 邮箱服务器端口号
        :param mail_user: 邮箱登录账号
        :param mail_auth_code: 邮箱授权码/密码
        :param sender: 邮件发送人
        :param recipients: 邮件接收人
        """
        self.sender = sender
        self.recipients = recipients
        # ---------- 连接smtp服务器并登录 ----------
        # 连接到smtp服务器
        self.smtp = smtplib.SMTP_SSL(host=host, port=port)

        # 登录smtp服务（邮箱账号+授权码登录）
        self.smtp.login(user=mail_user, password=mail_auth_code)

    def send_email(self, subject, content, file=None):
        """
        发送邮件
        :param subject: 邮件主题
        :param content: 邮件内容
        :param file: 邮件附件
        :return:
        """

        # ----------  构建邮件内容 ----------
        msg = MIMEMultipart()
        # 邮件主题
        msg['Subject'] = Header(subject, charset="utf8")
        # 邮件内容
        text = MIMEText(content, _subtype="html", _charset='utf8')
        # 收件人：是邮件中显示的收件人，不是实际的收件人
        msg['To'] = self.recipients
        # 发件人：是邮件中显示的发件人，不是实际的发件人
        msg['From'] = self.sender

        # 将构造的文本内容，添加到多组件邮件中
        msg.attach(text)

        # 构造邮件附件  问题：发送html样式没有了？
        # 读取报告中的内容，作为附件发送
        if file:
            with open(file, 'rb') as f:
                f_msg = f.read()
            att = MIMEApplication(f_msg)
            att.add_header('content-disposition', 'attachment', filename=file)
            msg.attach(att)
        # att = MIMEText(content, _subtype="html", _charset='utf8')
        # att["Content-Type"] = "appilication/octet-stream"
        # att.add_header('content-disposition', 'attachment', filename=file)
        # msg.attach(att)

        # ----------  发送邮件 ----------
        # from_addr是真正的发件人地址  to_addrs真正的收件人地址
        self.smtp.send_message(msg, from_addr=self.sender, to_addrs=self.recipients)

        # 关闭服务
        self.smtp.quit()
